package org.cn.lennon.mybatis.executors.impl.handler;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.cn.lennon.mybatis.config.MapperStatment;
import org.cn.lennon.mybatis.transcation.impl.connection.ConnestionPool;

public class PreparedStatmentHandler {

	private MapperStatment mapperStatemnt;

	public PreparedStatmentHandler(MapperStatment mapperStatemnt) {
		this.mapperStatemnt = mapperStatemnt;
	}

	public int update(Object[] queryObjects) throws SQLException {
		PreparedStatement prepareStatement = handlerQuery(queryObjects);
		return prepareStatement.executeUpdate();
	}

	public <T> T query(Object[] queryObjects) throws SQLException {
		PreparedStatement prepareStatement = handlerQuery(queryObjects);
		ResultSetHandler resultSetHandler = new ResultSetHandler(mapperStatemnt);
		return resultSetHandler.handler(prepareStatement);
	}

	public int insert(Object[] queryObjects) throws SQLException {
		PreparedStatement prepareStatement = handlerQuery(queryObjects);
		return prepareStatement.executeUpdate();
	}

	public int delete(Object[] queryObjects) throws SQLException {
		PreparedStatement prepareStatement = handlerQuery(queryObjects);
		return prepareStatement.executeUpdate();
	}

	private PreparedStatement handlerQuery(Object[] queryObjects) throws SQLException {
		PreparedStatement prepareStatement = ConnestionPool.getConnection().prepareStatement(mapperStatemnt.getSql());
		for (int i = 0; i < queryObjects.length; i++) {
			Integer index = i + 1;
			if (queryObjects[i] instanceof Integer) {
				prepareStatement.setInt(index, (Integer) queryObjects[i]);
			}
			if (queryObjects[i] instanceof String) {
				prepareStatement.setString(index, (String) queryObjects[i]);
			}
		}
		return prepareStatement;
	}
}
